<template>
  <div class="wrapper">
    <div class="search">
      <Form layout="inline" @finish="handleFinish">
        <Form.Item label="图书名称">
          <Input v-model:value="formSearch.fileName" placeholder="图书名称" allowClear>
            <template #prefix><UserOutlined style="color: rgb(0 0 0 / 25%)" /></template>
          </Input>
        </Form.Item>
        <Form.Item>
          <Button type="primary" html-type="submit" @click="getSearch"> 搜索 </Button>
        </Form.Item>
        <Form.Item>
          <Button @click="reset"> 重置 </Button>
        </Form.Item>
      </Form>
    </div>
    <div class="tableWrapeer">
      <div class="btnUnion">
        <Button type="primary" @click="addBook"> 新增图书 </Button>
      </div>
      <Table
        :columns="columns"
        :data-source="listData"
        :row-selection="rowSelection"
        :pagination="false"
      >
        <!-- eslint-disable-next-line vue/no-unused-vars -->
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.key === 'type'">
            <div>
              {{ getTypeName(text) }}
            </div>
          </template>
          <template v-if="column.key === 'action'">
            <span>
              <img src="" />
              <Button size="small" type="primary" @click="editBook(record.id)">
                <template #icon>
                  <EditOutlined />
                </template>
              </Button>
              &nbsp;&nbsp;
              <Popconfirm
                title="确认删除该图书吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="delBook(record.id)"
              >
                <Button size="small" type="danger">
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                </Button>
              </Popconfirm>
            </span>
          </template>
        </template>
      </Table>
      <Pagination
        v-model:current="formSearch.pageNum"
        v-model:page-size="formSearch.pageSize"
        :total="formSearch.total"
        show-size-changer
        :show-total="(total) => `总数: ${total}`"
        @change="onPageChange"
      />
    </div>
    <!-- 新增编辑抽屉 -->
    <Drawer
      v-model:visible="visible"
      width="30%"
      class="custom-class"
      style="color: red"
      :title="drawTit"
      placement="right"
      @after-visible-change="afterVisibleChange"
    >
      <Form :model="formObj">
        <Form.Item label="图书名称">
          <Input v-model:value="formObj.fileName" placeholder="请输入图书名称">
            <template #prefix><UserOutlined style="color: rgb(0 0 0 / 25%)" /></template>
          </Input>
        </Form.Item>
        <Form.Item label="图书标题">
          <Input v-model:value="formObj.title" placeholder="请输入图书标题">
            <template #prefix><UserOutlined style="color: rgb(0 0 0 / 25%)" /></template>
          </Input>
        </Form.Item>
        <Form.Item label="作者">
          <Input v-model:value="formObj.author" placeholder="请输入作者姓名">
            <template #prefix><UserOutlined style="color: rgb(0 0 0 / 25%)" /></template>
          </Input>
        </Form.Item>
        <Form.Item label="图书类型">
          <Select
            v-model:value="formObj.type"
            placeholder="请选择图书类型"
            allowClear
            :options="bookTypeList"
          />
        </Form.Item>
        <Form.Item label="背景图">
          <MyUpload :imgPic="formObj.cover" @change-cover="changeCover" />
        </Form.Item>
        <Form.Item :wrapper-col="{ span: 14, offset: 8 }">
          <Button @click="handlerClose"> 取消 </Button>
          <Button @click="btnOk" type="primary" style="margin-left: 20px"> 确认 </Button>
        </Form.Item>
      </Form>
    </Drawer>
  </div>
</template>
<script setup lang="ts">
  import {
    Pagination,
    Table,
    Form,
    Input,
    Button,
    Drawer,
    Select,
    message,
    Popconfirm,
  } from 'ant-design-vue';
  import MyUpload from '@/components/MyUpload/index.vue';
  import { booksApi } from '@/api/book/index';
  import { onMounted, ref } from 'vue';
  import { columns } from './book.data';
  import { EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { hasPermission } from '/@/utils/auth';
  import {
    BOOK_DELETE,
    BOOK_DELETE_MSG,
    BOOK_EDIT,
    BOOK_EDIT_MSG,
    BOOK_SEARCH,
    BOOK_SEARCH_MSG,
    BOOK_SUBMIT,
    BOOK_SUBMIT_MSG,
  } from '/@/utils/auth/permission-key';

  let listData = ref([]);
  const drawTit = ref('新建菜单');
  const formSearch = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });
  const formObj = ref({
    fileName: '',
    title: '',
    author: '',
    cover: [],
  });

  onMounted(() => {
    getBookTypeSelect();
    findList();
  });
  const getSearch = () => {
    if (!hasPermission(BOOK_SEARCH, BOOK_SEARCH_MSG)) return;
    findList();
  };
  const findList = async () => {
    const res = await booksApi.getBookList(formSearch.value);
    listData.value = res.result || [];
    formSearch.value.total = res.total;
    console.log('图书列表', res.result);
    console.log(formSearch.value.total);
  };
  const bookTypeList = ref([]);
  const getBookTypeSelect = async () => {
    const data = await booksApi.getBookTypeSelect();
    bookTypeList.value = data || [];
    console.log('下拉字典表data', bookTypeList.value);
  };
  const getTypeName = (text) => {
    return bookTypeList.value.find((item) => item.value === text)?.label;
  };

  const onPageChange = (current, size) => {
    formSearch.value.pageNum = current;
    formSearch.value.pageSize = size;
    findList();
  };

  // 检索
  const reset = () => {
    formSearch.value = {};
  };
  // 删除
  const delBook = async (id: number) => {
    if (!hasPermission(BOOK_DELETE, BOOK_DELETE_MSG)) return;
    await booksApi.deleteBook({ id: id });
    message.success('图书删除成功');
    findList();
  };

  // 弹窗
  const visible = ref(false);
  const addBook = () => {
    drawTit.value = '新建图书';
    console.log(formObj.value);

    visible.value = true;
  };
  const editBook = async (id) => {
    if (!hasPermission(BOOK_EDIT, BOOK_EDIT_MSG)) return;
    const data = await booksApi.getBookDetail({ id });
    formObj.value = {
      ...data,
      cover: [{ url: data.cover }],
    };
    drawTit.value = '编辑图书';
    visible.value = true;
  };
  const handlerClose = () => {
    formObj.value = {
      fileName: '',
      title: '',
      author: '',
      cover: [],
    };
    visible.value = false;
  };
  const btnOk = async () => {
    if (!hasPermission(BOOK_SUBMIT, BOOK_SUBMIT_MSG)) return;
    console.log(formObj.value);
    const submitData = {
      ...formObj.value,
      cover: formObj.value.cover?.[0]?.url || '', // 后端需要的字段可能是字符串
    };
    if (formObj.value.id) {
      // 编辑
      await booksApi.updateBook(submitData);
      message.success('更新图书成功');
    } else {
      // 新增
      await booksApi.createBook(submitData);
      message.success('创建图书成功');
    }
    handlerClose();
    findList();
  };
  const changeCover = (files) => {
    if (files[0].status === 'done') {
      formObj.value.cover = files;
      formObj.value.cover[0].url = files[0].url;
    }
  };
</script>

<style scoped lang="less">
  .wrapper {
    padding: 20px;

    .search {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #fff;
    }

    .tableWrapeer {
      padding: 20px;
      background-color: #fff;

      .btnUnion {
        margin-bottom: 10px;
      }
    }
  }

  .custom-class {
    .formFlex {
      display: flex !important;
    }

    .formFlex > *:last-child {
      margin-left: 20px;
    }
  }
</style>
